package com.link.base.base.dept.service;

import com.link.base.base.dept.dao.mybatis.mapper.DepartmentMapper;
import com.link.base.base.dept.model.Department;
import com.link.base.base.dept.model.DepartmentRelation;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.base.base.orgnization.service.OrgnizationService;
import com.link.core.basic.query.Sorter;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  unknwon
 * @date:   2018/11/9 16:20
 * @version 1.0
 */

@Service
public class DepartmentServiceImpl extends BasicServiceImpl<Department> implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private OrgnizationService orgnizationService;

    @Override
    public BasicMapper<Department> getBasicMapper() {
        return departmentMapper;
    }

    /**
     * 查询部门列表表排除主键为Id的部门和其子部门
     * @param entity
     * @return list
     * @throws Exception
     */
    @Override
    public List<Department> queryDepartmentListRemoveIdAndChildrenPage(Department entity) throws Exception {
        String dataBase = "mysql";
        if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBase)) {
            String str = departmentMapper.getDeptChildStr(entity);
            entity.setAttr6(str);
        }
        return departmentMapper.queryDepartmentListRemoveIdAndChildrenPage(entity);
    }

    /**
     * 查询根部门
     * @param entity
     * @return list
     * @throws Exception
     */
    @Override
    public Department queryRoot(Department entity) throws Exception {
        return departmentMapper.queryRoot(entity);
    }

    /**
     * 根据根部门查询部门树
     * @param entity
     * @throws Exception
     */
    @Override
    public void queryTreeByRoot(Department entity) throws Exception {
        // treeDepartmentList(entity);
        treeDeptList(entity);
    }

    private void treeDeptList(Department entity) throws Exception {
        Department t = new Department();
        t.setPageFlag(false);
        QueryParams qps = new QueryParams();
        List<Sorter> sorters = new ArrayList<>();
        Sorter sorter = new Sorter();
        sorter.setProperty("deptCode");
        sorter.setDirection("ASC");
        sorters.add(sorter);
        qps.setSorters(sorters);
        t.setQps(qps);
        List<Department> tempList = departmentMapper.queryByExamplePage(t);
        printTreeDeptList(tempList ,entity);
    }

    private void printTreeDeptList(List<Department> tempList, Department entity) throws BasicServiceException {
        if (null == entity.getId()) {
            throw new ServiceException("DEPT-001");
        }
        List<Department> childList = new ArrayList<>();
        for (Department temp : tempList) {
            if (entity.getId().equals(temp.getParentDeptId())) {
                childList.add(temp);
            }
        }
        entity.setChildren(childList);
        for ( Department dept : childList) {
            printTreeDeptList(tempList,dept);
        }
    }

    /**
     * 递归查询部门树结构
     *
     * @throws Exception
     */
    private void treeDepartmentList(Department entity) throws Exception {
        QueryParams params = new QueryParams();
        params.addFilter(new Filter("parentDeptId", String.valueOf(entity.getId())));
        params.setPageFlag(false);
        Department t = (Department) BasicModel.transformClass(Department.class, params);
        List<Department> tempList = departmentMapper.queryByExamplePage(t);
        for (Department temp : tempList) {
            treeDepartmentList(temp);
        }
        entity.setChildren(tempList);
    }



    /**
     * 用于画结构图
     * @param entity
     * @throws Exception
     */
    @Override
    public void queryTreeByRoot1(Department entity) throws Exception {
        treeDepartmentList1(entity);
    }

    private void treeDepartmentList1(Department entity) throws Exception {


        QueryParams params = new QueryParams();
        params.addFilter(new Filter("parentDeptId", String.valueOf(entity.getId())));
        params.setPageFlag(false);
        Department t = (Department) BasicModel.transformClass(Department.class, params);
        List<Department> tempList = departmentMapper.queryByExamplePage(t);
        for (Department temp : tempList) {

            treeDepartmentList1(temp);
        }
        entity.setChildren(tempList);
    }

    @Override
    public void beforUpsert(Department entity) throws Exception {
        super.beforUpsert(entity);
        if (StringUtils.isBlank(entity.getIsEffective())) {
            entity.setIsEffective("Y");
        }
    }

    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void insert(Department entity) throws BasicServiceException {
        try {
            QueryParams params = new QueryParams();
            Department t = (Department) BasicModel.transformClass(Department.class, params);
            //如果父部门没有指定，则添加默认父部门
            if (null == entity.getParentDeptId()) {
                //获取根部门的ID
                Long parentDeptId = departmentMapper.queryRoot(t).getId();
                entity.setParentDeptId(parentDeptId);
            }
            super.insert(entity);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new BasicServiceException(e.getMessage());
        }
    }

    /**
     * 根据ID递归删除该记录以及其子对象
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void deleteWithChildById(Department entity) throws Exception {
        beforDelete(entity);
        checkId(entity);
        QueryParams params = new QueryParams();
        params.setLoginCorpId(UserUtil.getUser().getLoginCorpId());
        params.setPageFlag(false);
        removeWithChilds(entity, params);
    }


    /**
     * 递归删除
     * @param entity
     * @param params
     * @throws Exception
     */
    private void removeWithChilds(Department entity, QueryParams params) throws Exception {
        try {
            deleteById(entity);
            params.addFilter(new Filter("parentDeptId", String.valueOf(entity.getId())));
            Department t = (Department) BasicModel.transformClass(Department.class, params);
            List<Department> list = departmentMapper.queryByExamplePage(t);
            for (Department department : list) {
                this.removeWithChilds(department, params);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * <p>根据集成ID在本系统中查找部门信息，无则返回空</p>
     * @author yrf
     * @param model
     * @return
     * @throws Exception
     */
    @Override
    public Department getDept(Department model) throws Exception {
        Long crmId = model.getCrmId();
        String integrationId = model.getIntegrationId();

        if (StringUtils.isBlank(integrationId)) {
            throw new ServiceException("PUBLIC-036");
        }
        Department dept = null;
        if (!(null == crmId)) {
            Department example = new Department();
            example.setId(crmId);

            dept = queryById(example);
            if (dept == null) {
                throw new ServiceException("DEPT-003", crmId.toString());
            } else if (!integrationId.equals(dept.getIntegrationId())) {
                throw new ServiceException("DEPT-002");
            }
        } else {
            Department example = new Department();
            example.setIntegrationId(integrationId);
            example.setPageFlag(false);
            List<Department> list = queryByExamplePage(example);
            if (list != null && list.size() > 0) {
                if (list.size() == 1) {
                    dept = list.get(0);
                } else {
                    throw new ServiceException("DEPT-004", integrationId);
                }
            }
        }
        return dept;
    }

    /**
     * <p>根据父部门集成ID在本系统中查找父部门，无则报错</p>
     * @author yrf
     * @param model
     * @return
     * @throws Exception
     */
    @Override
    public Department getParentDept(Department model) throws Exception {
        String parentIntegrationId = model.getParentIntegrationId();
        Department dept = null;
        if (StringUtils.isBlank(parentIntegrationId)) {
            //父部门集成ID为空，则挂到根节点下，根部门需要先初始化
            Department example = new Department();
            example.setPageFlag(false);

            dept = queryRoot(example);
            if (dept == null) {
                throw new ServiceException("DEPT-005");
            }
        } else {
            //在本系统中查找父部门
            Department example = new Department();
            example.setIntegrationId(parentIntegrationId);
            example.setPageFlag(false);
            List<Department> list = queryByExamplePage(example);
            if (list == null || list.size() == 0) {
                throw new ServiceException("DEPT-006", parentIntegrationId);
            } else if (list.size() == 1) {
                dept = list.get(0);
            } else {
                throw new ServiceException("DEPT-007", parentIntegrationId);
            }
        }
        return dept;
    }


    /**
     * <p>根据组织集成ID在本系统中查找组织</p>
     * @author yrf
     * @param model
     * @return
     * @throws Exception
     */
    @Override
    public Orgnization getOrg(Department model) throws Exception {
        Orgnization org = null;
        String orgIntegrationId = model.getOrgIntegrationId();
        if (!StringUtils.isBlank(orgIntegrationId)) {
            Orgnization example = new Orgnization();
            example.setIntegrationId(orgIntegrationId);
            example.setPageFlag(false);
            List<Orgnization> list = orgnizationService.queryByExamplePage(example);
            if (list == null || list.size() == 0) {
                if (orgIntegrationId.equals(model.getIntegrationId())) {
                    //关联组织为其本身
                    return null;
                }
                throw new ServiceException("DEPT-008", orgIntegrationId);
            } else if (list.size() == 1) {
                org = list.get(0);
            } else {
                throw new ServiceException("DEPT-009", orgIntegrationId);
            }
        } else {
            throw new ServiceException("DEPT-010");
        }
        return org;
    }

    /**
     * 获取多层级部门关联关系
     * @author 姚江漪
     * @date 2019/04/02 23:20
     * @param departmentRelation
     */
    @Override
    public List<DepartmentRelation> queryAreaRegionPage(DepartmentRelation departmentRelation) throws Exception {
        return departmentMapper.queryAreaRegionPage(departmentRelation);
    }


    /**
     * 提供app根据部门获取战区、片区、大区信息
     * @author 姚江漪
     * @date 2019/04/17 17:32
     */
    @Override
    public Map<String,Object> queryAPPUserAreaRegion(Department entity) throws Exception {
        Map<String,Object> result = new HashMap<>();
        Long detpId = entity.getId();
        if (null == detpId) {
            throw new BasicServiceException("部门信息为空，请联系管理员查看！");
        }
        Department dept = new Department();
        dept.setDeptType("SalesArea");
        dept.setId(detpId);
        List<Department> salesAreaDeptList = departmentMapper.queryTierDept(dept);
        if (salesAreaDeptList.size() <= 0) {
            throw new BasicServiceException("部门对应的战区信息为空，请联系管理员查看！");
        }
        dept.setDeptType("SalesRegion");
        List<Department> salesRegionDeptList = departmentMapper.queryTierDept(dept);
        if (salesRegionDeptList.size() <= 0) {
            throw new BasicServiceException("部门对应的片区信息为空，请联系管理员查看！");
        }
        dept.setDeptType("Region");
        List<Department> regionDeptList = departmentMapper.queryTierDept(dept);
        if (regionDeptList.size() <= 0) {
            throw new BasicServiceException("部门对应的大区信息为空，请联系管理员查看！");
        }
        // 战区信息
        result.put("salesAreaId",salesAreaDeptList.get(0).getId());
        result.put("salesArea",salesAreaDeptList.get(0).getText());
        // 片区信息
        result.put("salesRegionId",salesRegionDeptList.get(0).getId());
        result.put("salesRegion",salesRegionDeptList.get(0).getText());
        // 大区信息
        result.put("regionId",regionDeptList.get(0).getId());
        result.put("region",regionDeptList.get(0).getText());
        return result;
    }
}
